package cn.org.xuanzp.examples.v1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 
 * @author hy
 * @createTime 2021-04-17 12:43:42
 * @description 一个使用netty模拟实现的ftp服务器
 *
 */
public class NettyFtpServer {
	private ServerBootstrap bootstrap ;
	private EventLoopGroup mainEventLoopGroup;
	private EventLoopGroup otherEventLoopGroup;
	private ChannelInitializer<Channel> channelInitializer;
	private final int port;

	public NettyFtpServer(int port) {
		this.port = port;
		this.mainEventLoopGroup=new NioEventLoopGroup();
		this.otherEventLoopGroup=new NioEventLoopGroup();
		bootstrap = new ServerBootstrap();
		channelInitializer =new NettyFtpServerChannelInitializer();
	}
	
	public void start() throws InterruptedException {
		bootstrap
		.group(mainEventLoopGroup,otherEventLoopGroup)
		.channel(NioServerSocketChannel.class)
		.childHandler(channelInitializer);

		ChannelFuture channelFuture = bootstrap.bind(port).sync();
		if (channelFuture.isSuccess()) {
			System.out.println("服务端启动成功");
		} else {
			System.out.println("服务端启动失败");
			channelFuture.cause().printStackTrace();
			close();
		}
	}
	
	public void close() {
		mainEventLoopGroup.shutdownGracefully();
		otherEventLoopGroup.shutdownGracefully();
	}
}